package dns;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.MXRecord;
import org.xbill.DNS.Record;
import org.xbill.DNS.Type;

public class DnsResolver {
	
	public DnsResolver() {
		// Do nothing
	}
	
	private String extractHost(String email) throws Exception{
		int separator = email.indexOf('@');
		if (separator < 0) {
			throw new Exception("Invalid email");
		}
		else {
			return email.substring(separator + 1, email.length());
		}
	}
	
	
	private InetAddress getHardcoded(String host) throws Exception {
    	byte addr[] = {(byte)192, (byte)168, (byte)3, (byte)11};    	
    	InetAddress hostname = InetAddress.getByAddress(addr);
    	return hostname;
	}
	
	private InetAddress getResolved(String host) throws Exception {		
    	Record [] records = new Lookup(host, Type.MX).run();
    	ArrayList<MXRecord> sar = new ArrayList<MXRecord>();
    	for (Record rec : records) {
    		sar.add((MXRecord) rec);
    	}
    	Collections.sort(sar, new MxComparator());    	
    	String hostname = sar.get(0).getTarget().toString();
    	return InetAddress.getByName(hostname);
    			
	}
	
	// Filter only MX records!!
	public InetAddress getServerIP(String email) throws Exception{
		try {
			String host = extractHost(email);				
			return getHardcoded(host);
			//return getResolved(host);
		}
		catch (Exception e){
			throw new Exception("Cannot resolve mail server address");
		}
	}
	
}
